function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}

function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,

        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}

var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate;
let operationList=[];
let salesmanList=[];
let deptOperationList=[];
let deptSalesmanList=[];
(function () {
    let treeList = getCurrentDepartmentUser();
    if(treeList && treeList.list){
        let userTree = getAllJson(treeList.list);
        operationList=getxmselect("#executorCode","executor",userTree)
        salesmanList=getxmselect("#salesmanCode","salesman",userTree)
    }else{
        operationList=getxmselect("#executorCode","executor",[{name: user.name, value: user.code}])
        salesmanList=getxmselect("#salesmanCode","salesman",[{name: user.name, value: user.code}])
    }

    //获取当前用户所属部门树()
    let currentDeptTreeList = getAllUserDepartmentTree();
    if (currentDeptTreeList && currentDeptTreeList.list) {
        let deptTree = getAllJson(currentDeptTreeList.list);
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", deptTree);
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", deptTree);
    } else {
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", [{name: user.name, value: user.code}]);
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", [{name: user.name, value: user.code}]);
    }

})()

let bpmId = '';
let bpmStatus = '0';//审批状态  0 未审核 1 审批中 2审核完成

let startInspectDate= laydate.render({
    elem: '#startInspectTime',//选择器结束时间
    type: 'date',
    min:"1970-1-1",//设置min默认最小值
    done: function(value,date){
        startInspectDate.config.max={
            year:date.year,
            month:date.month-1,
            date: date.date,
            hours: 0,
            minutes: 0,
            seconds : 0
        }
    }
});

let endInspectDate=laydate.render({
    elem: '#endInspectTime',
    type: 'date',
    max:"2099-12-31",//设置一个默认最大值
    done: function(value, date){
        endInspectDate.config.min ={
            year:date.year,
            month:date.month-1,
            date: date.date,
            hours: 0,
            minutes: 0,
            seconds : 0
        };
    }
});
let endDate= laydate.render({
    elem: '#endCreateTime',//选择器结束时间
    type: 'date',
    min:"1970-1-1",//设置min默认最小值
    done: function(value,date){
        startDate.config.max={
            year:date.year,
            month:date.month-1,
            date: date.date,
            hours: 0,
            minutes: 0,
            seconds : 0
        }
    }
});

let startDate=laydate.render({
    elem: '#startCreateTime',
    type: 'date',
    max:"2099-12-31",//设置一个默认最大值
    done: function(value, date){
        endDate.config.min ={
            year:date.year,
            month:date.month-1,
            date: date.date,
            hours: 0,
            minutes: 0,
            seconds : 0
        };
    }
});

let userList;
//操作员、业务员
$.ajax({
    type : 'POST',
    url:'user/getAllUserNameAndCode',
    dataType:"json",
    contentType: 'application/json;charset=utf-8',
    success:function(res){
        if(res.status == 200){
            if(res.data){
                userList = res.data;
            }else{
                layer.msg(res.msg,{icon:0});
            }
        }else{
            layer.msg(res.msg,{icon:4});
        }
    }
});

//制单公司
let complaintUnit = [];
$.ajax({
    url: "company/getAllMakerUnit",
    success: function (res) {
        if (res.status == 200) {
            complaintUnit = res.data;
            $.each(res.data, function (index, item) {
                if(item){
                    $("#complaintUnit").append(new Option(item.name, item.code));
                }
            });
            form.render('select');
        } else {
            layer.msg(res.msg, {icon: 5});
        }
    }
});
let stageList = getdictionary(6,38);//验货阶段列表
let inspectTypeList = getdictionary(6,39);//验货类型列表

let isMsn="否";

layer.ready(function () {
    $.ajax({
        url: 'billChange/isMsn',
        type: 'GET',
        async: false, // 同步
        success: function (date) {
            isMsn=date.data
        }
    })

    table.render({
        elem: '#inspectionselect'
        ,url: 'inspectCargo/selectInspectCargoList'
        ,method:'post'
        ,contentType: 'application/json;charset=utf-8'
        ,request: {
            pageName: 'pageNum'
            ,limitName: 'pageSize'
        }
        ,id: 'inspectiontableid'
        ,toolbar: '#inspectiontoolbar'
        ,cols: [[
            {checkbox: true, fixed: true}
            ,{field:'loadPlanNo', title:'出运计划单号',width:120,sort:true}
            ,{field:'boxStatus', title:'单据类型',width:120,sort:true,
                templet: function(data) {
                    switch (data.boxStatus) {
                        case "1": return "草稿箱";
                        case "2": return "待批箱";
                        case "3": return "已批箱";
                        case "4": return "完成箱";
                        case "5": return "垃圾箱";
                        case "0": return "待验货箱";
                        default : return "";
                    }
                }
            }
            ,{field:'oddNumber', title:'验货单号',width:170,sort:true,event: "inspectionnumber"}
            ,{field:'inspectType', title:'验货类型',width:120,
                templet: function(data) {
                    let name = "";
                    $.each(inspectTypeList, function(index, item) {
                        if (data.inspectType==item.code){
                            name = item.name;
                            return ;
                        }
                    });
                    return name;
                }
            }
            ,{field:'inspectTime', title:'验货日期',width:120,sort:true}
            ,{field:'address', title:'验货地址',width:120}
            ,{field:'timeLimit', title:'要求期限',width:120,sort:true}
            ,{field:'company', title:'验货公司',width:120}
            ,{field:'cost', title:'验货费用',width:120,sort:true}
            ,{field:'stage', title:'验货阶段',width:120,
                templet: function(data) {
                    let name = "";
                    $.each(stageList, function(index, item) {
                        if (data.stage==item.code){
                            name = item.name;
                            return ;
                        }
                    });
                    return name;
                }
            }

            ,{field:'inspector', title:'业务员',width:120,
                templet: function(data) {
                    let name = "";
                    $.each(userList, function(index, item) {
                        if (data.inspector==item.code){
                            name = item.name;
                            return ;
                        }
                    });
                    return name;
                }
            }
            ,{field:'complaintUnit', title:'制单公司',width:120,
                templet: function(data) {
                    let name = "";
                    $.each(complaintUnit, function(index, item) {
                        if (data.complaintUnit==item.code){
                            name = item.name;
                            return ;
                        }
                    });
                    return name;
                }
            }
            ,{field:'executor', title:'操作员',width:120,
                templet: function(data) {
                    let name = "";
                    $.each(userList, function(index, item) {
                        if (data.executor==item.code){
                            name = item.name;
                            return ;
                        }
                    });
                    return name;
                }
            }
            ,{field:'remark', title:'备注',width:120}
            // ,{fixed: 'right', width:240, toolbar: '#inspectionEditor', title:'操作'}
            ,{fixed: 'right', width:240, title:'操作',templet: function(d){
                    // 单据状态/类型（1：草稿箱，2：待批箱，3：已批箱，4：完成箱，5垃E圾箱）
                    if(isMsn=="是"){//管理员
                        var html="<div>"
                        if(d.boxStatus==0){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"generate\">生成验货单</a>";
                        }
                        if(d.boxStatus==1 || d.boxStatus==2){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"update\">修改</a>";
                        }
                        if(d.boxStatus==1){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"submits\">提交审批</a>" +
                                "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delect\">删除</a>"
                        }
                        if(d.boxStatus==2){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"through\">审批通过</a>"
                        }
                        if(d.boxStatus==2 || d.boxStatus==3){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"backtothe\">审批退回</a>"
                        }
                        if(d.boxStatus==3){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"complete\">完成</a>"
                        }
                        return html+"</div>";
                    }else {
                        var html = "<div>"
                        if(d.boxStatus==0){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"generate\">生成验货单</a>";
                        }
                        if (d.boxStatus == 1) {
                            html = html + "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"update\">修改</a>" +
                                "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"submits\">提交审批</a>" +
                                "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delect\">删除</a>"
                        }
                        if(d.boxStatus==3){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"complete\">完成</a>"
                        }
                        return html + "</div>";
                    }
                }
            }
        ]]
        ,height: $(document).height() - $('#inspectionselect').offset().top - 50
        ,page: true
        ,parseData: function(res) {
            let code = 0 , count = 0, data = null;
            if(res.status!=200 &&res.status!=0){
                layer.msg(res.msg);
            }else{
                code = res.status;
                count = res.total;
                data = res.data;
            }
            return {
                "code": code,
                "count": count,
                "data": data
            }
        }
    });
});
table.on('tool(inspectiontable)', function(obj){
    var data = obj.data;
    if(obj.event ==='generate'){
        parent.intab("views/jsp/other/tpl/newupinspection.jsp?id="+obj.data.id+"&newType="+1,"生成验货单")
    }else if(obj.event === 'update') {
        parent.intab("views/jsp/other/tpl/newupinspection.jsp?id="+obj.data.id,"修改验货质检")
    }else if(obj.event === 'delect'){
        layer.confirm('确定删除吗', function (index) {
            if(deleteById(data.id)){
                obj.del();
                layer.close(index);
            }
        });
        return;
    }else if(obj.event === 'submits'){
        layer.confirm('确定提交审批吗', function (index) {
            bpmId=startProcess(data.id);
            update(data.id,data.boxStatus*1+1,"提交审批");
        });
    }else if(obj.event === 'through'){
        layer.confirm('确定审批通过吗', function (index) {
            update(data.id,data.boxStatus*1+1,"审批通过");
        });
    }else if(obj.event === 'backtothe'){
        layer.confirm('确定审批退回吗', function (index) {
            update(data.id,data.boxStatus-1,"审批退回");
        });
    }else if(obj.event === 'complete'){
        layer.confirm('确定完成吗', function (index) {
            update(data.id,data.boxStatus*1+1,"审批完成");
        });
    }else if(obj.event === 'reduction'){
        layer.confirm('确定还原吗', function (index) {
            update(data.id,1,"审批还原");
        });
    }else if (obj.event === "inspectionnumber"){
        parent.intab("views/jsp/other/tpl/viewinspection.jsp?id="+obj.data.id,"验货质检明细")
    }
});

form.on('submit(submitform)', function(data){
    table.reload('inspectiontableid',{where: data.field });
    return false;
});

table.on('toolbar(inspectiontable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
        case 'news':
            parent.intab("views/jsp/other/tpl/newupinspection.jsp","新增验货质检")
            break;
        case 'dels':
            var data=checkStatus.data,delList=[];
            data.forEach(function(n,i){
                delList.push(n.id);
            });
            if(delList.length>0){
                layer.confirm('确定删除所选项吗？',function (index) {
                    var cbList = table.cache["inspectiontableid"];
                    for(var i = 0;i<cbList.length;i++){
                        delList.forEach((item, index) => {
                            //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                            if (typeof (cbList[i]) != "undefined"&&item == cbList[i].id) {
                                cbList.splice(i, 1);
                            }
                        })
                    }
                    table.reload("inspectiontableid", {
                        data: cbList,
                    });
                    layer.msg('删除成功');
                })
            }else{
                layer.msg('请选择需要删除的行');
            }
            break;
    };
});

// $("#statistical").on("click",function () {
//     parent.intab("views/jsp/other/tpl/inspectCargoStatistics.jsp","验货质检统计")
// });
layui.use(['dropdown'], function () {
    let dropdown = layui.dropdown;
    dropdown.onFilter("statistics", function (event) {
        switch (event) {
            case "s1":
                parent.intab("views/jsp/other/tpl/inspectCargoStatistics.jsp","验货质检统计")
                break
            case "s2":
                parent.intab("views/jsp/ExportBusiness/tpl/purchaseStatistics2.jsp","采购排产及计划统计")
                break
        }
    });
})


function deleteById(delId) {
    let tf = false;
    $.ajax({
        type: 'POST',
        url: 'inspectCargo/delete/'+delId,
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (res) {
            if (res.status == 200) {
                if(res.data){
                    tf = true;
                    layer.msg("删除成功",{icon: 1});
                    table.reload('inspectiontableid');
                }else{
                    layer.msg("删除失败",{icon: 4});
                }
            }else{
                layer.msg("删除失败",{icon: 2});
            }
        },
        error: function (data) {
            layer.msg("删除异常",{icon: 5});
        }
    });
    return tf;
}

//boxStatus 1 草稿 2 待批  3:已批 4 完成 5 垃圾
function update(id,boxStatus,titleName) {
    let tf = false;
    let msgInfo = "";
    let dataJson = {
        "id":id,
        "boxStatus":boxStatus,
        "bpmId":bpmId,
        "bpmStatus":bpmStatus,
    };
    $.ajax({
        type: 'POST',
        data: JSON.stringify(dataJson),
        url: 'inspectCargo/updateBoxStatusBykey',
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (da) {
            if (da.status == 200) {
                tf = true;
                msgInfo = titleName+"成功!"
                table.reload('inspectiontableid');
            }else{
                msgInfo = titleName+"失败!"
            }
        },
        error: function (data) {
            msgInfo = titleName+"异常!"
        }
    });
    layer.msg(msgInfo);
    return tf;
}

function startProcess(bid) {
    let res="";
    $.ajax({
        type : 'get',
        data:{"processDefId":'inspectCargo',"bid":bid,"variables":null},
        url:'process/startProcess',
        async:false,
        dataType:"json",
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                res=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return res;
}

document.getElementById('clear').onclick = function(){
    operationList.setValue([ ]);
    salesmanList.setValue([ ]);
    deptOperationList.setValue([ ]);
    deptSalesmanList.setValue([ ]);
};